package com.marketing.tenant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.marketing.tenant.entity.SubscriptionPlan;
import com.marketing.tenant.mapper.SubscriptionPlanMapper;
import com.marketing.tenant.service.SubscriptionPlanService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订阅计划服务实现
 * 
 * @author Marketing System
 * @since 2024-09-25
 */
@Service
public class SubscriptionPlanServiceImpl implements SubscriptionPlanService {
    
    private static final Logger log = LoggerFactory.getLogger(SubscriptionPlanServiceImpl.class);
    
    @Autowired
    private SubscriptionPlanMapper subscriptionPlanMapper;
    
    @Override
    @Transactional
    public boolean createPlan(SubscriptionPlan plan) {
        try {
            // 检查计划名称是否已存在
            SubscriptionPlan existingPlan = getPlanByName(plan.getPlanName());
            if (existingPlan != null) {
                throw new RuntimeException("订阅计划名称已存在: " + plan.getPlanName());
            }
            
            // 设置创建时间
            plan.setCreateTime(LocalDateTime.now());
            plan.setUpdateTime(LocalDateTime.now());
            
            // 默认设置为启用状态
            if (plan.getStatus() == null) {
                plan.setStatus(1);
            }
            
            int result = subscriptionPlanMapper.insert(plan);
            log.info("创建订阅计划成功，计划名称: {}, ID: {}", plan.getPlanName(), plan.getId());
            return result > 0;
        } catch (Exception e) {
            log.error("创建订阅计划失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建订阅计划失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public boolean updatePlan(SubscriptionPlan plan) {
        try {
            // 检查计划是否存在
            SubscriptionPlan existingPlan = getPlanById(plan.getId());
            if (existingPlan == null) {
                throw new RuntimeException("订阅计划不存在，ID: " + plan.getId());
            }
            
            // 如果修改了计划名称，检查新名称是否已存在
            if (!existingPlan.getPlanName().equals(plan.getPlanName())) {
                SubscriptionPlan duplicatePlan = getPlanByName(plan.getPlanName());
                if (duplicatePlan != null && !duplicatePlan.getId().equals(plan.getId())) {
                    throw new RuntimeException("订阅计划名称已存在: " + plan.getPlanName());
                }
            }
            
            // 更新时间
            plan.setUpdateTime(LocalDateTime.now());
            
            int result = subscriptionPlanMapper.updateById(plan);
            log.info("更新订阅计划成功，计划名称: {}, ID: {}", plan.getPlanName(), plan.getId());
            return result > 0;
        } catch (Exception e) {
            log.error("更新订阅计划失败: {}", e.getMessage(), e);
            throw new RuntimeException("更新订阅计划失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public boolean deletePlan(Long planId) {
        try {
            SubscriptionPlan plan = getPlanById(planId);
            if (plan == null) {
                throw new RuntimeException("订阅计划不存在，ID: " + planId);
            }
            
            // 软删除：设置状态为已删除
            plan.setDeleted(1);
            plan.setUpdateTime(LocalDateTime.now());
            
            int result = subscriptionPlanMapper.updateById(plan);
            log.info("删除订阅计划成功，计划名称: {}, ID: {}", plan.getPlanName(), planId);
            return result > 0;
        } catch (Exception e) {
            log.error("删除订阅计划失败: {}", e.getMessage(), e);
            throw new RuntimeException("删除订阅计划失败: " + e.getMessage());
        }
    }
    
    @Override
    public SubscriptionPlan getPlanById(Long planId) {
        try {
            return subscriptionPlanMapper.selectById(planId);
        } catch (Exception e) {
            log.error("根据ID查询订阅计划失败: {}", e.getMessage(), e);
            return null;
        }
    }
    
    @Override
    public SubscriptionPlan getPlanByName(String planName) {
        try {
            if (!StringUtils.hasText(planName)) {
                return null;
            }
            LambdaQueryWrapper<SubscriptionPlan> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SubscriptionPlan::getPlanName, planName);
            return subscriptionPlanMapper.selectOne(wrapper);
        } catch (Exception e) {
            log.error("根据名称查询订阅计划失败: {}", e.getMessage(), e);
            return null;
        }
    }
    
    @Override
    public IPage<SubscriptionPlan> getActivePlans(Page<SubscriptionPlan> page) {
        try {
            LambdaQueryWrapper<SubscriptionPlan> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SubscriptionPlan::getStatus, 1)
                   .eq(SubscriptionPlan::getDeleted, 0)
                   .orderByAsc(SubscriptionPlan::getPlanName);
            return subscriptionPlanMapper.selectPage(page, wrapper);
        } catch (Exception e) {
            log.error("分页查询可用订阅计划失败: {}", e.getMessage(), e);
            throw new RuntimeException("查询订阅计划失败: " + e.getMessage());
        }
    }
    
    @Override
    public List<SubscriptionPlan> getAllActivePlans() {
        try {
            LambdaQueryWrapper<SubscriptionPlan> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SubscriptionPlan::getStatus, 1)
                   .eq(SubscriptionPlan::getDeleted, 0)
                   .orderByAsc(SubscriptionPlan::getPlanName);
            return subscriptionPlanMapper.selectList(wrapper);
        } catch (Exception e) {
            log.error("查询所有可用订阅计划失败: {}", e.getMessage(), e);
            throw new RuntimeException("查询订阅计划失败: " + e.getMessage());
        }
    }
    
    @Override
    public List<SubscriptionPlan> getPlansByPriceRange(Double minPrice, Double maxPrice) {
        try {
            LambdaQueryWrapper<SubscriptionPlan> wrapper = new LambdaQueryWrapper<>();
            wrapper.ge(SubscriptionPlan::getPrice, minPrice)
                   .le(SubscriptionPlan::getPrice, maxPrice)
                   .eq(SubscriptionPlan::getStatus, 1)
                   .eq(SubscriptionPlan::getDeleted, 0)
                   .orderByAsc(SubscriptionPlan::getPrice);
            return subscriptionPlanMapper.selectList(wrapper);
        } catch (Exception e) {
            log.error("根据价格范围查询订阅计划失败: {}", e.getMessage(), e);
            throw new RuntimeException("查询订阅计划失败: " + e.getMessage());
        }
    }
    
    @Override
    public List<SubscriptionPlan> getPlansByFeature(String feature) {
        try {
            LambdaQueryWrapper<SubscriptionPlan> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(SubscriptionPlan::getFeatures, feature)
                   .eq(SubscriptionPlan::getStatus, 1)
                   .eq(SubscriptionPlan::getDeleted, 0)
                   .orderByAsc(SubscriptionPlan::getPlanName);
            return subscriptionPlanMapper.selectList(wrapper);
        } catch (Exception e) {
            log.error("根据功能模块查询订阅计划失败: {}", e.getMessage(), e);
            throw new RuntimeException("查询订阅计划失败: " + e.getMessage());
        }
    }
    
    @Override
    public List<SubscriptionPlan> getRecommendedPlans() {
        try {
            LambdaQueryWrapper<SubscriptionPlan> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SubscriptionPlan::getStatus, 1)
                   .eq(SubscriptionPlan::getDeleted, 0)
                   .orderByAsc(SubscriptionPlan::getPlanName);
            return subscriptionPlanMapper.selectList(wrapper);
        } catch (Exception e) {
            log.error("查询推荐订阅计划失败: {}", e.getMessage(), e);
            throw new RuntimeException("查询推荐计划失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public boolean enablePlan(Long planId) {
        try {
            SubscriptionPlan plan = getPlanById(planId);
            if (plan == null) {
                throw new RuntimeException("订阅计划不存在，ID: " + planId);
            }
            
            plan.setStatus(1);
            plan.setUpdateTime(LocalDateTime.now());
            
            int result = subscriptionPlanMapper.updateById(plan);
            log.info("启用订阅计划成功，ID: {}", planId);
            return result > 0;
        } catch (Exception e) {
            log.error("启用订阅计划失败: {}", e.getMessage(), e);
            throw new RuntimeException("启用订阅计划失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public boolean disablePlan(Long planId) {
        try {
            SubscriptionPlan plan = getPlanById(planId);
            if (plan == null) {
                throw new RuntimeException("订阅计划不存在，ID: " + planId);
            }
            
            plan.setStatus(0);
            plan.setUpdateTime(LocalDateTime.now());
            
            int result = subscriptionPlanMapper.updateById(plan);
            log.info("禁用订阅计划成功，ID: {}", planId);
            return result > 0;
        } catch (Exception e) {
            log.error("禁用订阅计划失败: {}", e.getMessage(), e);
            throw new RuntimeException("禁用订阅计划失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public boolean setRecommended(Long planId, boolean recommended) {
        // 这个方法在当前数据库结构中不适用，因为我们没有推荐字段
        return true;
    }
}